<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/8 0008
 * Time: 10:54
 */

namespace App\Http\Controllers\Web\ActivityTrigger;

use App\App\Services\Web\UserService;
use App\Http\Controllers\Controller;
use App\Models\ActivityTrigger\ActivityTriggerService;
use Illuminate\Http\Request;

class ActivityTriggerController extends Controller
{
    public function index()
    {
        return view('web.activityTrigger.list');
    }

    public function getActivityTriggerList(Request $request, ActivityTriggerService $activityTriggerService, UserService $userService)
    {
        $loginUser = $userService->getLoginUser();
        $user_id = $loginUser['id'];
        $res = $activityTriggerService->getActivityTriggerListByPage($request, $user_id);
        return $this->respondJson($res);
    }

    public function edit(Request $request, ActivityTriggerService $activityTriggerService)
    {
        $id = $request->input('id');
        if ($request->isMethod('post')) {
            $input = $request->request->all();
            $update = [];
            if (!is_null($input['status'])) {
                $update['status'] = $input['status'];
            }
            $res = $activityTriggerService->saveActivityTriggerById($update, $id);
            return $this->respondJson([
                'message'=>'保存成功'
            ]);
        }
        return $this->respondJson([
            'message'=>'保存失败'
        ]);
    }

    public function editActivityTrigger(Request $request, ActivityTriggerService $activityTriggerService)
    {
        $id = $request->input('id');
        $this->validate($request, [
            'id' =>'required'
        ], [
            'id.required'=>'触发ID不能为空'
        ]);
        $triggerData = $activityTriggerService->getActivityTriggerById($id);
        return view('web.activityTrigger.edit', ['triggerData'=>$triggerData]);
    }

    public function delete(Request $request, ActivityTriggerService $activityTriggerService)
    {
        $ids = $request->input('ids');
        $this->validate($request, [
            'ids' =>'required'
        ], [
            'ids.required'=>'触发ID不能为空'
        ]);
        $res = $activityTriggerService->deleteActivityTriggers($ids);
        return  $this->respondJson([
            'message'=>'删除成功'
        ]);
    }

    public function add()
    {
        return view('web.activityTrigger.add');
    }

    public function _validateActivityTrigger($request, $action='add')
    {
        if ($action == 'edit') {
            $this->validate($request, [
                'id' => 'required',
            ], [
                'id.required' => '触发ID参数为空',
                ]);
        }
        $this->validate($request, [
            'rule_name' => 'required',
            'platform' => 'required',
            'act_name' => 'required',
            'act_type' => 'required',
            'show_img' => 'required',
            'float_type' => 'required',
            'float_time' => 'required',
            'begin_time' => 'required',
            'end_time' => 'required',
            'trigger_times' => 'required',
            'trigger_condition' => 'required'
        ], [
            'rule_name.required' => '请添加活动规则',
            'platform.required' => '请选择平台',
            'act_name.required' => '请选择活动',
            'act_type.required' => '请选择活动类型',
            'show_img.required' => '请选择触发形式',
            'float_type.required' => '请选择活动类型',
            'float_time.required' => '请填写悬浮时间',
            'begin_time.required' => '请选择触发开始时间',
            'end_time.required' => '请选择触发结束时间',
            'trigger_times.required' => '请添加触发次数',
            'trigger_condition.required' => '请选择触发条件'
        ]);
    }
    public function _getActivityTriggerDataFormat($request)
    {
        $act_type = $request->input('act_type');
        $data = [
            'rule_name'=>$request->input('rule_name'),
            'act_id'=>($act_type == 1)?$request->input('act_id'):0,
            'act_name'=>$request->input('act_name'),
            'act_type'=>$act_type,
            'show_img'=>$request->input('show_img'),
            'float_type'=>$request->input('float_type'),
            'float_time'=>$request->input('float_time'),
            'begin_time'=>strtotime($request->input('begin_time')),
            'end_time'=>strtotime($request->input('end_time')),
            'trigger_times'=>$request->input('trigger_times'),
            'trigger_times_unit'=>$request->input('trigger_times_unit'),
            'trigger_condition'=>$request->input('trigger_condition'),
            'target'=>$request->input('target'),
            'weight'=>$request->input('weight'),
            'totop'=>$request->input('totop'),
            'toleft'=>$request->input('toleft'),
            'checked_small_img'=>$request->input('checked_small_img'),
            'checked_big_img'=>$request->input('checked_big_img'),
            'big_img'=> json_encode($request->input('big_img')),
            'small_img'=>json_encode($request->input('small_img'))
        ];
        return $data;
    }

    /**
     * 新增触发
     * @param Request $request
     * @param ActivityTriggerService $activityTriggerService
     * @param UserService $userService
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request, ActivityTriggerService $activityTriggerService, UserService $userService)
    {
        if ($request->isMethod('post')) {
            $this->_validateActivityTrigger($request);
        }

        $act_type = $request->input('act_type');
        if ($act_type == 2) {
            $rule = '/^((https|http)?:\/\/)[^\s]+/';
            $act_name = $request->input('act_name');
            if (!preg_match($rule, $act_name)) {
                return $this->respondJson(['message' => '自有活动格式错误', 'code' => 1]);
            }
        }
        $platformArray = $request->input('platform');
        $platform = 0;
        foreach ($platformArray as $key=>$val) {
            $platform = $platform | $val; //转成二进制储存
        }

        $loginUser = $userService->getLoginUser();

        $data = $this->_getActivityTriggerDataFormat($request);
        $data['user_id'] = $loginUser['id'];
        $data['platform'] = $platform;

        $res = $activityTriggerService->create($data);
        return $this->respondJson(['message'=>'新建触发成功']);
    }

    /**
     * 编辑触发
     * @param Request $request
     * @param ActivityTriggerService $activityTriggerService
     * @return \Illuminate\Http\JsonResponse
     */
    public function modify(Request $request, ActivityTriggerService $activityTriggerService)
    {
        $this->_validateActivityTrigger($request, "edit");
        $input = $request->request->all();
        if ($input['act_type'] == 2) {
            $rule = '/^((https|http)?:\/\/)[^\s]+/';
            if (!preg_match($rule, $input['act_name'])) {
                return $this->respondJson(['message' => '自有活动格式错误', 'code' => 1]);
            }
        }
        $platformArray = $input['platform'];
        $platform = 0;
        foreach ($platformArray as $key=>$val) {
            $platform = $platform | $val;   //转成二进制储存
        }
        $update = [];
        if (!is_null($input)) {
            $update = $this->_getActivityTriggerModifyData($input);
            $update['platform'] = $platform;
        }
        $id = $request->input('id');
        $res = $activityTriggerService->saveActivityTriggerById($update, $id);
        if ($res) {
            return $this->respondJson(['message' => '保存成功']);
        } else {
            return $this->respondJson(['message' => '保存失败']);
        }
    }

    /**
     * 组装修改的数据
     * @param $input
     * @return mixed
     */
    public function _getActivityTriggerModifyData($input)
    {
        $update['rule_name'] = $input['rule_name'];
        $update['act_id'] = $input['act_id'];
        $update['act_name'] = $input['act_name'];
        $update['act_type'] = $input['act_type'];
        $update['show_img'] = $input['show_img'];
        $update['begin_time'] = strtotime($input['begin_time']);
        $update['end_time'] = strtotime($input['end_time']);
        $update['trigger_times'] = $input['trigger_times'];
        $update['trigger_times_unit'] = $input['trigger_times_unit'];
        $update['trigger_condition'] = $input['trigger_condition'];
        $update['target'] = $input['target'];
        $update['float_time'] = $input['float_time'];
        $update['float_type'] = $input['float_type'];
        $update['weight'] = $input['weight'];
        $update['totop'] = $input['totop'];
        $update['toleft'] = $input['toleft'];
        $update['checked_big_img'] = $input['checked_big_img'];
        $update['checked_small_img'] = $input['checked_small_img'];
        $update['big_img'] = isset($input['big_img'])?json_encode($input['big_img']):'';
        $update['small_img'] = isset($input['small_img'])?json_encode($input['small_img']):'';

        return $update;
    }
}
